package com.zsc.newbuds.utils;

import com.zsc.newbuds.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author D
 * token工具类
 */
@Component
public class TokenUtil {
    /**
     * 签名私匙
     */
    @Value("${jwt.config.key}")
    private String key;
    /**
     * 过期时间
     */
    @Value("${jwt.config.expirationTime}")
    private Long expirationTime;

    /**
     * 创建token
     * @param id
     * @param phone
     * @param map
     * @return
     */
    public String createToken(String id, String phone, Map<String,Object> map){
        //设置失效时间
        long nowTime = System.currentTimeMillis();
        long time = nowTime+expirationTime;

        //创建jwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(phone)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);

        //根据Map设置claims
        for(Map.Entry<String, Object> entry: map.entrySet()){
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }

        //过期时间
        jwtBuilder.setExpiration(new Date(time));

        //创建token
        return jwtBuilder.compact();

    }

    /**
     * 解析token 获取claims
     * @param token
     * @return
     */
    public Claims parseJwt(String token){
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

    public Map<String, Object> getMapByUser(User user){
        Map<String, Object> map = new HashMap<>();
        map.put("password",user.getPassword());
        map.put("integral",user.getIntegral());
        map.put("address",user.getAddress());
        map.put("userName",user.getUserName());
        return map;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getExpirationTime() {
        return expirationTime;
    }

    public void setExpirationTime(Long expirationTime) {
        this.expirationTime = expirationTime;
    }
}
